package ai.peanut.one.api.mq.mqTestTopic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class TopicTestConfig {
    // # 可以匹配之后所有的
    public static final String dispearKey = "dispear.#" ;
    public static final String refundKey = "refund.#" ;

    public static final String exchangeName = "exchangeTopic" ;
    public static final String exchangeRefund = "exchangeRefundTopicccc" ;
    public static final String dispearQuueName = "dispearQueue" ;

    public static final String refundQueueName = "refundQueue" ;


    private static final Logger log = LoggerFactory.getLogger(TopicTestConfig.class);
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Bean
    public AmqpTemplate amqpTemplate()  {

        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> log.info("消息发送成功:correlationData({}),ack({}),cause({})", correlationData, ack, cause));
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> log.info("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}", exchange, routingKey, replyCode, replyText, message));
        return rabbitTemplate;
    }



    @Bean
    public Queue queueMessageDispear() {
//
//        Map<String, Object> params = new HashMap<>();
//        // x-dead-letter-exchange 声明了队列里的死信转发到的DLX名称，
//        params.put("x-dead-letter-exchange", exchangeRefund);
//        // x-dead-letter-routing-key 声明了这些死信在转发时携带的 routing-key 名称。
//        // 最后会根据routing-key和交换机 来确定进去queue
//        params.put("x-dead-letter-routing-key", refundKey);
//        // TTL 设置
//        params.put("x-message-ttl", 3 * 60 * 1000);
//        return new Queue(dispearQuueName, true, false, false, params);
//

        return new Queue(dispearQuueName);
    }
    @Bean
    public Queue queueMessageRefund() {

        return new Queue(refundQueueName);
    }

    @Bean
    TopicExchange exchange() {
        return new TopicExchange(exchangeName);
    }

    @Bean
    TopicExchange exchangeRefund() {
        return new TopicExchange(exchangeRefund);
    }


    @Bean
    Binding bindingExchangeMessage1( TopicExchange exchange) {
        return BindingBuilder.bind(queueMessageDispear()).to(exchange).with(dispearKey);
    }
    @Bean
    Binding bindingExchangeMessages2() {
        return BindingBuilder.bind(queueMessageRefund()).to(exchangeRefund()).with(refundKey);
    }

}
